<template>
  <div class="big-file-download">
    <!-- 搜索和筛选 -->
    <div class="download-header">
      <div class="search-box">
        <input
          v-model="searchQuery"
          placeholder="搜索文件名..."
          @input="handleSearch"
          class="search-input"
        />
        <button @click="handleSearch" class="search-btn">搜索</button>
      </div>

      <div class="filter-options">
        <select v-model="filterType" @change="handleFilter" class="filter-select">
          <option value="all">所有文件</option>
          <option value="video">视频文件</option>
          <option value="audio">音频文件</option>
          <option value="document">文档</option>
          <option value="image">图片</option>
        </select>

        <select v-model="sortBy" @change="handleSort" class="sort-select">
          <option value="name">按名称</option>
          <option value="size">按大小</option>
          <option value="date">按日期</option>
        </select>
      </div>
    </div>

    <!-- 文件列表 -->
    <div class="file-list">
      <div v-for="file in filteredFiles" :key="file.id" class="file-item">
        <div class="file-icon">
          <i :class="getFileIcon(file.type)"></i>
        </div>

        <div class="file-details">
          <div class="file-name">{{ file.name }}</div>
          <div class="file-meta">
            <span class="file-size">{{ formatFileSize(file.size) }}</span>
            <span class="file-date">{{ formatDate(file.uploadTime) }}</span>
            <span class="file-type">{{ file.type }}</span>
          </div>
        </div>

        <div class="download-progress" v-if="file.downloading">
          <div class="progress-info">
            <div class="progress-bar">
              <div class="progress-fill" :style="{ width: file.progress + '%' }"></div>
            </div>
            <span class="progress-text">{{ file.progress.toFixed(1) }}%</span>
          </div>

          <div class="download-speed" v-if="file.downloadSpeed">
            速度: {{ file.downloadSpeed }}
          </div>

          <div class="download-time" v-if="file.remainingTime">
            剩余: {{ file.remainingTime }}
          </div>
        </div>

        <div class="file-actions">
          <button
            v-if="!file.downloading"
            @click="startDownload(file)"
            class="btn-download"
            :disabled="file.downloading"
          >
            下载
          </button>

          <button
            v-if="file.downloading"
            @click="pauseDownload(file)"
            class="btn-pause"
          >
            暂停
          </button>

          <button
            v-if="file.paused"
            @click="resumeDownload(file)"
            class="btn-resume"
          >
            继续
          </button>

          <button
            v-if="file.downloading || file.paused"
            @click="cancelDownload(file)"
            class="btn-cancel"
          >
            取消
          </button>

          <button
            @click="previewFile(file)"
            class="btn-preview"
            v-if="isPreviewable(file.type)"
          >
            预览
          </button>

          <button
            @click="showFileInfo(file)"
            class="btn-info"
          >
            详情
          </button>
        </div>

        <!-- 下载状态 -->
        <div class="download-status">
          <span v-if="file.completed" class="status-completed">✅ 下载完成</span>
          <span v-if="file.error" class="status-error">❌ 下载失败: {{ file.error }}</span>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="filteredFiles.length === 0" class="empty-state">
      <i class="empty-icon">📁</i>
      <p>暂无文件</p>
    </div>

    <!-- 下载统计 -->
    <div class="download-stats" v-if="downloadList.length > 0">
      <div class="stats-grid">
        <div class="stat-card">
          <div class="stat-value">{{ activeDownloads }}</div>
          <div class="stat-label">正在下载</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{ completedDownloads }}</div>
          <div class="stat-label">已完成</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{ formatFileSize(totalDownloaded) }}</div>
          <div class="stat-label">已下载</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{ averageSpeed }}</div>
          <div class="stat-label">平均速度</div>
        </div>
      </div>
    </div>

    <!-- 文件详情模态框 -->
    <div v-if="showInfoModal" class="modal-overlay" @click="closeInfoModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>文件详情</h3>
          <button @click="closeInfoModal" class="modal-close">×</button>
        </div>
        <div class="modal-body" v-if="selectedFile">
          <div class="info-item">
            <label>文件名:</label>
            <span>{{ selectedFile.name }}</span>
          </div>
          <div class="info-item">
            <label>文件大小:</label>
            <span>{{ formatFileSize(selectedFile.size) }}</span>
          </div>
          <div class="info-item">
            <label>文件类型:</label>
            <span>{{ selectedFile.type }}</span>
          </div>
          <div class="info-item">
            <label>上传时间:</label>
            <span>{{ formatDate(selectedFile.uploadTime) }}</span>
          </div>
          <div class="info-item">
            <label>MD5校验:</label>
            <span class="md5-hash">{{ selectedFile.md5 }}</span>
          </div>
          <div class="info-item">
            <label>下载次数:</label>
            <span>{{ selectedFile.downloadCount || 0 }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { fileService } from '@/services/fileService';
import { chunkManager } from '@/router/chunkManager';
import { usePreviewStore } from '@/stores/previewStore';

export default {
  name: 'BigFileDownload',
  data() {
    return {
      files: [],
      downloadList: [],
      searchQuery: '',
      filterType: 'all',
      sortBy: 'date',
      showInfoModal: false,
      selectedFile: null,
      refreshInterval: null
    };
  },
  computed: {
    filteredFiles() {
      let filtered = this.files;

      // 搜索过滤
      if (this.searchQuery) {
        filtered = filtered.filter(file =>
          file.name.toLowerCase().includes(this.searchQuery.toLowerCase())
        );
      }

      // 类型过滤
      if (this.filterType !== 'all') {
        filtered = filtered.filter(file => this.getFileCategory(file.type) === this.filterType);
      }

      // 排序
      filtered.sort((a, b) => {
        switch (this.sortBy) {
          case 'name':
            return a.name.localeCompare(b.name);
          case 'size':
            return b.size - a.size;
          case 'date':
          default:
            return new Date(b.uploadTime) - new Date(a.uploadTime);
        }
      });

      return filtered;
    },

    activeDownloads() {
      return this.downloadList.filter(d => d.downloading).length;
    },

    completedDownloads() {
      return this.downloadList.filter(d => d.completed).length;
    },

    totalDownloaded() {
      return this.downloadList.reduce((total, d) => total + (d.downloadedSize || 0), 0);
    },

    averageSpeed() {
      const active = this.downloadList.filter(d => d.downloading && d.downloadSpeed);
      if (active.length === 0) return '0 KB/s';

      const totalSpeed = active.reduce((sum, d) => {
        const speed = parseFloat(d.downloadSpeed) || 0;
        return sum + speed;
      }, 0);

      return (totalSpeed / active.length).toFixed(1) + ' KB/s';
    }
  },
  methods: {
    // 初始化文件列表
    async initFileList() {
      try {
        const response = await fileService.getFileList();
        this.files = response.data.map(file => ({
          ...file,
          downloading: false,
          paused: false,
          completed: false,
          progress: 0,
          downloadedSize: 0,
          downloadSpeed: null,
          remainingTime: null,
          error: null
        }));
      } catch (error) {
        console.error('获取文件列表失败:', error);
        this.$message.error('获取文件列表失败');
      }
    },

    // 开始下载
    async startDownload(file) {
      try {
        file.downloading = true;
        file.paused = false;
        file.completed = false;
        file.error = null;

        // 添加到下载列表
        if (!this.downloadList.find(d => d.id === file.id)) {
          this.downloadList.push(file);
        }

        const downloadItem = await chunkManager.downloadFile(
          file.name,
          file.url || `/file/download/${file.name}`,
          {
            onProgress: (progress, speed, remaining) => {
              this.updateDownloadProgress(file, progress, speed, remaining);
            },
            onComplete: (blob) => {
              this.handleDownloadComplete(file, blob);
            },
            onError: (error) => {
              this.handleDownloadError(file, error);
            }
          }
        );

        file.downloadId = downloadItem.id;

      } catch (error) {
        this.handleDownloadError(file, error);
      }
    },

    // 暂停下载
    pauseDownload(file) {
      file.downloading = false;
      file.paused = true;
      chunkManager.pauseDownload(file.downloadId);
    },

    // 继续下载
    resumeDownload(file) {
      file.downloading = true;
      file.paused = false
      chunkManager.resumeDownload(file.downloadId);
    },

        cancelDownload(file) {
          file.downloading = false;
          file.paused = false;
          file.progress = 0;
          chunkManager.cancelDownload(file.downloadId);

          // 从下载列表移除
          const index = this.downloadList.findIndex(d => d.id === file.id);
          if (index !== -1) {
            this.downloadList.splice(index, 1);
          }
        },

        // 更新下载进度
        updateDownloadProgress(file, progress, speed, remaining) {
          file.progress = progress;
          file.downloadSpeed = speed;
          file.remainingTime = remaining;
          file.downloadedSize = (file.size * progress) / 100;
        },

        // 处理下载完成
        handleDownloadComplete(file, blob) {
          file.downloading = false;
          file.completed = true;
          file.progress = 100;

          // 创建下载链接
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = file.name;
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          window.URL.revokeObjectURL(url);

          this.$message.success(`文件 "${file.name}" 下载完成`);
          this.$emit('download-completed', file);
        },

        // 处理下载错误
        handleDownloadError(file, error) {
          console.error('下载错误:', error);
          file.downloading = false;
          file.error = error.message || '下载失败';

          this.$message.error(`文件 "${file.name}" 下载失败: ${error.message}`);
          this.$emit('download-error', file, error);
        },

        // 预览文件
        previewFile(file) {
          if (!this.isPreviewable(file.type)) {
            this.$message?.warning('该文件暂不支持在线预览');
            return;
          }
          const previewStore = usePreviewStore();
          previewStore.openPreview({
            fileName: file.name,
            displayName: file.displayName || file.name,
            fileType: this.getFileCategory(file.type) === 'audio' ? 'audio' : undefined
          });
        },

        // 显示文件详情
        showFileInfo(file) {
          this.selectedFile = file;
          this.showInfoModal = true;
        },

        // 关闭详情模态框
        closeInfoModal() {
          this.showInfoModal = false;
          this.selectedFile = null;
        },

        // 处理搜索
        handleSearch() {
          // 搜索逻辑已在计算属性中处理
        },

        // 处理筛选
        handleFilter() {
          // 筛选逻辑已在计算属性中处理
        },

        // 处理排序
        handleSort() {
          // 排序逻辑已在计算属性中处理
        },

        // 获取文件图标
        getFileIcon(fileType) {
          const type = fileType?.toLowerCase() || '';
          if (type.includes('video')) return 'fas fa-file-video';
          if (type.includes('audio')) return 'fas fa-file-audio';
          if (type.includes('image')) return 'fas fa-file-image';
          if (type.includes('pdf')) return 'fas fa-file-pdf';
          if (type.includes('word')) return 'fas fa-file-word';
          if (type.includes('excel')) return 'fas fa-file-excel';
          if (type.includes('zip') || type.includes('rar')) return 'fas fa-file-archive';
          return 'fas fa-file';
        },

        // 获取文件分类
        getFileCategory(fileType) {
          const type = fileType?.toLowerCase() || '';
          if (type.includes('video')) return 'video';
          if (type.includes('audio')) return 'audio';
          if (type.includes('image')) return 'image';
          if (type.includes('pdf') || type.includes('word') || type.includes('excel') || type.includes('text')) {
            return 'document';
          }
          return 'other';
        },

        // 检查文件是否可预览
        isPreviewable(fileType) {
          const type = fileType?.toLowerCase() || '';
          return type.includes('image') ||
                 type.includes('pdf') ||
                 type.includes('text') ||
                 type.includes('audio');
        },

        // 格式化文件大小
        formatFileSize(bytes) {
          if (bytes === 0) return '0 B';

          const k = 1024;
          const sizes = ['B', 'KB', 'MB', 'GB'];
          const i = Math.floor(Math.log(bytes) / Math.log(k));

          return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        },

        // 格式化日期
        formatDate(timestamp) {
          if (!timestamp) return '';
          const date = new Date(timestamp);
          return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
        },

        // 清理下载任务
        cleanupDownloads() {
          this.downloadList.forEach(file => {
            if (file.downloading) {
              this.cancelDownload(file);
            }
          });
        }
      },

      async mounted() {
        await this.initFileList();

        // 定时刷新下载进度
        this.refreshInterval = setInterval(() => {
          this.downloadList.forEach(file => {
            if (file.downloading) {
              // 更新速度显示等
            }
          });
        }, 1000);
      },

      beforeUnmount() {
        if (this.refreshInterval) {
          clearInterval(this.refreshInterval);
        }
        this.cleanupDownloads();
      }
    };
    </script>

    <style scoped>
    .big-file-download {
      max-width: 1000px;
      margin: 0 auto;
      padding: 20px;
    }

    .download-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      flex-wrap: wrap;
      gap: 15px;
    }

    .search-box {
      display: flex;
      gap: 10px;
    }

    .search-input {
      padding: 8px 12px;
      border: 1px solid #ddd;
      border-radius: 4px;
      min-width: 200px;
    }

    .search-btn, .filter-select, .sort-select {
      padding: 8px 12px;
      border: 1px solid #ddd;
      border-radius: 4px;
      background: white;
      cursor: pointer;
    }

    .filter-options {
      display: flex;
      gap: 10px;
    }

    .file-list {
      space-y: 10px;
    }

    .file-item {
      display: flex;
      align-items: center;
      padding: 15px;
      border: 1px solid #e0e0e0;
      border-radius: 8px;
      margin-bottom: 10px;
      background: white;
      gap: 15px;
    }

    .file-icon {
      font-size: 24px;
      color: #666;
      min-width: 40px;
    }

    .file-details {
      flex: 1;
      min-width: 0;
    }

    .file-name {
      font-weight: bold;
      color: #333;
      margin-bottom: 5px;
      word-break: break-word;
    }

    .file-meta {
      display: flex;
      gap: 15px;
      font-size: 12px;
      color: #666;
    }

    .file-meta span {
      white-space: nowrap;
    }

    .download-progress {
      flex: 2;
      min-width: 200px;
    }

    .progress-info {
      display: flex;
      align-items: center;
      gap: 10px;
      margin-bottom: 5px;
    }

    .progress-bar {
      flex: 1;
      height: 6px;
      background: #f0f0f0;
      border-radius: 3px;
      overflow: hidden;
    }

    .progress-fill {
      height: 100%;
      background: #409eff;
      transition: width 0.3s ease;
    }

    .progress-text {
      font-size: 12px;
      color: #666;
      min-width: 50px;
    }

    .download-speed, .download-time {
      font-size: 11px;
      color: #999;
    }

    .file-actions {
      display: flex;
      gap: 8px;
      flex-wrap: wrap;
    }

    .file-actions button {
      padding: 6px 12px;
      border: 1px solid #ddd;
      border-radius: 4px;
      background: white;
      cursor: pointer;
      font-size: 12px;
      white-space: nowrap;
    }

    .btn-download { color: #409eff; border-color: #409eff; }
    .btn-pause { color: #e6a23c; border-color: #e6a23c; }
    .btn-resume { color: #67c23a; border-color: #67c23a; }
    .btn-cancel { color: #f56c6c; border-color: #f56c6c; }
    .btn-preview { color: #909399; border-color: #909399; }
    .btn-info { color: #909399; border-color: #909399; }

    .download-status {
      margin-top: 5px;
    }

    .status-completed { color: #67c23a; font-size: 12px; }
    .status-error { color: #f56c6c; font-size: 12px; }

    .empty-state {
      text-align: center;
      padding: 60px 20px;
      color: #999;
    }

    .empty-icon {
      font-size: 48px;
      margin-bottom: 10px;
    }

    .download-stats {
      margin-top: 30px;
      padding: 20px;
      background: #f5f7fa;
      border-radius: 8px;
    }

    .stats-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
      gap: 15px;
    }

    .stat-card {
      background: white;
      padding: 15px;
      border-radius: 6px;
      text-align: center;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }

    .stat-value {
      font-size: 24px;
      font-weight: bold;
      color: #409eff;
      margin-bottom: 5px;
    }

    .stat-label {
      font-size: 12px;
      color: #666;
    }

    /* 模态框样式 */
    .modal-overlay {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0,0,0,0.5);
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 1000;
    }

    .modal-content {
      background: white;
      border-radius: 8px;
      max-width: 500px;
      width: 90%;
      max-height: 80vh;
      overflow-y: auto;
    }

    .modal-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px;
      border-bottom: 1px solid #e0e0e0;
    }

    .modal-header h3 {
      margin: 0;
      color: #333;
    }

    .modal-close {
      background: none;
      border: none;
      font-size: 24px;
      cursor: pointer;
      color: #999;
    }

    .modal-body {
      padding: 20px;
    }

    .info-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 0;
      border-bottom: 1px solid #f0f0f0;
    }

    .info-item label {
      font-weight: bold;
      color: #333;
      min-width: 80px;
    }

    .info-item span {
      color: #666;
      word-break: break-all;
      text-align: right;
    }

    .md5-hash {
      font-family: monospace;
      font-size: 12px;
    }

    @media (max-width: 768px) {
      .download-header {
        flex-direction: column;
        align-items: stretch;
      }

      .search-box, .filter-options {
        justify-content: center;
      }

      .file-item {
        flex-direction: column;
        align-items: stretch;
        gap: 10px;
      }

      .file-details, .download-progress {
        min-width: auto;
      }

      .file-actions {
        justify-content: center;
      }

      .stats-grid {
        grid-template-columns: repeat(2, 1fr);
      }

      .file-meta {
        flex-wrap: wrap;
        gap: 8px;
      }
    }
    </style>
